package org.jeecg.modules.coupon.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.coupon.entity.Coupon;
import org.jeecg.modules.coupon.entity.CouponOrder;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.service.ICouponOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.coupon.service.ICouponService;
import org.jeecg.modules.coupon.service.IMyCouponService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.service.IBalanceService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.DateUtil;
import org.jeecg.modules.system.util.MenJinUtil;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.entity.Zixishi;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 优惠券订单
 * @Author: jeecg-boot
 * @Date:   2024-06-28
 * @Version: V1.0
 */
@Api(tags="优惠券订单")
@RestController
@RequestMapping("/coupon/couponOrder")
@Slf4j
public class CouponOrderController extends JeecgController<CouponOrder, ICouponOrderService> {
	@Autowired
	private ICouponOrderService couponOrderService;
	@Autowired
	private ICouponService couponService;
	@Autowired
	private IBalanceService balanceService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IMyCouponService myCouponService;
	@Autowired
	private ISysDictService sysDictService;
	/**
	 * 分页列表查询
	 *
	 * @param couponOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "优惠券订单-分页列表查询")
	@ApiOperation(value="优惠券订单-分页列表查询", notes="优惠券订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CouponOrder>> queryPageList(CouponOrder couponOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CouponOrder> queryWrapper = QueryGenerator.initQueryWrapper(couponOrder, req.getParameterMap());
		Page<CouponOrder> page = new Page<CouponOrder>(pageNo, pageSize);
		IPage<CouponOrder> pageList = couponOrderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param couponOrder
	 * @return
	 */
	@AutoLog(value = "优惠券订单-添加")
	@ApiOperation(value="优惠券订单-添加", notes="优惠券订单-添加")
	//@RequiresPermissions("org.jeecg.modules:sr_coupon_order:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CouponOrder couponOrder) {
		couponOrderService.save(couponOrder);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param couponOrder
	 * @return
	 */
	@AutoLog(value = "优惠券订单-编辑")
	@ApiOperation(value="优惠券订单-编辑", notes="优惠券订单-编辑")
	//@RequiresPermissions("org.jeecg.modules:sr_coupon_order:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CouponOrder couponOrder) {
		couponOrderService.updateById(couponOrder);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "优惠券订单-通过id删除")
	@ApiOperation(value="优惠券订单-通过id删除", notes="优惠券订单-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:sr_coupon_order:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		couponOrderService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "优惠券订单-批量删除")
	@ApiOperation(value="优惠券订单-批量删除", notes="优惠券订单-批量删除")
	//@RequiresPermissions("org.jeecg.modules:sr_coupon_order:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.couponOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "优惠券订单-通过id查询")
	@ApiOperation(value="优惠券订单-通过id查询", notes="优惠券订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CouponOrder> queryById(@RequestParam(name="id",required=true) String id) {
		CouponOrder couponOrder = couponOrderService.getById(id);
		if(couponOrder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(couponOrder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param couponOrder
    */
    //@RequiresPermissions("org.jeecg.modules:sr_coupon_order:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CouponOrder couponOrder) {
        return super.exportXls(request, couponOrder, CouponOrder.class, "优惠券订单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("sr_coupon_order:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CouponOrder.class);
    }

	 @AutoLog(value = "卡券订单-添加")
	 @ApiOperation(value="卡券订单-添加", notes="卡券订单-添加")
	 @PostMapping(value = "/doOrder")
	 public Result<CouponOrder> doOrder(@RequestBody Coupon order) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 SysUser sysUserEntity = sysUserService.getById(sysUser.getId());
		 String phone = sysUserEntity.getPhone();
		 if(StringUtils.isBlank(phone)) {
			 return Result.error("未填写手机号，不允许购买");
		 }

		 Coupon coupon = couponService.getById(order.getId());
		 if(coupon==null) {
			 return Result.error("卡券信息不存在，请重新选择");
		 }

		 Integer limitCnt = coupon.getLimitCnt();
		 if(null != limitCnt) {
			 long cnt = couponOrderService.count(new LambdaQueryWrapper<CouponOrder>().eq(CouponOrder::getSysUserId, sysUser.getId()).eq(CouponOrder::getCouponId, coupon.getId()).eq(CouponOrder::getOrderStatus, "1"));
			 if(cnt >= limitCnt) {
				 return Result.error("该卡券每人限购"+limitCnt + "张");
			 }
		 }
		 CouponOrder couponOrder = new CouponOrder();
		 couponOrder.setCouponId(coupon.getId())
				 .setOrderName(coupon.getName())
				 .setOrderNum("" + FillRuleUtil.executeRule("shop_order_num", new JSONObject()))
				 .setOrderStatus("0")
				 .setOrderMoney(coupon.getDisAmt().toPlainString())
				 .setSysUserId(sysUser.getId());
		 couponOrderService.save(couponOrder);
		 return Result.OK(couponOrder);
	 }

	 @ApiOperation(value="订单支付使用余额", notes="订单支付使用余额")
	 @PostMapping(value = "/payorder")
	 public Result<String> payOrder(@RequestBody Map paramMap) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String orderNum = "" + paramMap.get("orderNum");
		 CouponOrder order = couponOrderService.getOne(new LambdaQueryWrapper<CouponOrder>().eq(CouponOrder::getSysUserId,sysUser.getId()).eq(CouponOrder::getOrderNum, orderNum));
		 if(null == order){
			 return Result.error("订单不存在，请确认");
		 }
		 Balance balance = balanceService.getOne(new LambdaQueryWrapper<Balance>().eq(Balance::getSysUserId, order.getSysUserId()));
		 if(null == balance){
			 return Result.error("余额不足，请确认");
		 }
		 Float orderMoney = Float.valueOf(order.getOrderMoney());
		 Float money = balance.getBalance().floatValue();
		 if(money < orderMoney){
			 return Result.error("余额不足，请确认");
		 }
		 Coupon coupon = couponService.getById(order.getCouponId());
		 if(coupon==null || coupon.getStatus() == 0 ||coupon.getCnt()<1){
			 return Result.error("卡券不允许购买，请确认");
		 }
		couponOrderService.payOrder(sysUser,balance,order,coupon);

		 return Result.ok("支付成功");
	 }
}
